// 管理mdc 单例

import 'package:flutter_deer/database/beans/get_config_guns_entity.dart';
import 'package:flutter_deer/database/tables.dart';
import 'package:flutter_deer/mvvm/base_net_provider.dart';
import 'package:flutter_deer/ui/setting/setting_page4_mdc.dart';
import 'package:flutter_deer/util/input_formatter/mny_format.dart';
import 'package:flutter_deer/util/socket/BaseMdcControl.dart';
import 'package:flutter_deer/util/socket/mdc_hb_json_control.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:rxdart/rxdart.dart';

import 'mdc_default_control.dart';

class MdcProvider extends BaseNetProvider {
  final RxList<MdcSetBean> mdcList = <MdcSetBean>[].obs;

  // 剑云类型的mdc
  MdcDefaultControlImpl? _mdcDefaultControl;
  MdcHbJsonControlImpl? _mdcHbJsonControlImpl;

  // 监听状态流
  final stateStream = BehaviorSubject<AppOrderBean>();
  // 监听订单流
  final orderStream = BehaviorSubject<AppOrderBean>();
  // 监听mdc链接状态
  final mdcStateStream = BehaviorSubject<MapEntry<String, bool>>();

  final _subscriptions = CompositeSubscription();

  @override
  void onInit() {
    super.onInit();
    final mdcSetBeanList = MdcSetBean.getMdcSetBeanList();
    mdcList.assignAll(mdcSetBeanList);
  }

  @override
  void onReady() {
    super.onReady();
    for (final mdcClient in mdcList) {

      if (mdcClient.linkType == 1) {
        _mdcDefaultControl ??= MdcDefaultControlImpl();
        _mdcDefaultControl?.initAndStart(mdcClient.ip, mdcClient.port);

        final listen = _mdcDefaultControl?.mdcStateStreamController.stream.listen((event) {
          mdcStateStream.add(event);
          // 刷新列表
          final index = mdcList.indexWhere((element) => '${element.ip}:${element.port}' == event.key);
          if (index != -1) {
            mdcList[index].connected = event.value;
          }
          mdcList.refresh();
        });
        if (listen != null) {
          _subscriptions.add(listen);
        }

        final orderListen = _mdcDefaultControl?.orderStreamController.stream.listen((event) {
          orderStream.add(event);
        });
        if (orderListen != null) {
          _subscriptions.add(orderListen);
        }

        final stateListen = _mdcDefaultControl?.stateStreamController.stream.listen((event) {
          stateStream.add(event);
        });
        if (stateListen != null) {
          _subscriptions.add(stateListen);
        }
      }

      if (mdcClient.linkType == 3) {
        _mdcHbJsonControlImpl ??= MdcHbJsonControlImpl();
        _mdcHbJsonControlImpl?.initAndStart(mdcClient.ip, mdcClient.port);

        final listen = _mdcHbJsonControlImpl?.mdcStateStreamController.stream.listen((event) {
          mdcStateStream.add(event);
          // 刷新列表
          final index = mdcList.indexWhere((element) => '${element.ip}:${element.port}' == event.key);
          if (index != -1) {
            mdcList[index].connected = event.value;
          }
          mdcList.refresh();
        });
        if (listen != null) {
          _subscriptions.add(listen);
        }

        final orderListen = _mdcHbJsonControlImpl?.orderStreamController.stream.listen((event) {
          orderStream.add(event);
        });
        if (orderListen != null) {
          _subscriptions.add(orderListen);
        }

        final stateListen = _mdcHbJsonControlImpl?.stateStreamController.stream.listen((event) {
          stateStream.add(event);
        });
        if (stateListen != null) {
          _subscriptions.add(stateListen);
        }
      }
    }
  }

  // 添加一个集线器
  void addMdcHub(MdcSetBean mdcClient) {
    if (mdcClient.linkType == 1) {
      _mdcDefaultControl ??= MdcDefaultControlImpl();
      _mdcDefaultControl?.initAndStart(mdcClient.ip, mdcClient.port);
    }
    if (mdcClient.linkType == 3) {
      _mdcHbJsonControlImpl ??= MdcHbJsonControlImpl();
      _mdcHbJsonControlImpl?.initAndStart(mdcClient.ip, mdcClient.port);
    }
  }

  // 移除一个集线器
  void removeMdcHub(MdcSetBean mdcClient) {
    if (mdcClient.linkType == 1) {
      _mdcDefaultControl?.delThisMdc(mdcClient.ip, mdcClient.port);
    }
    if (mdcClient.linkType == 3) {
      _mdcHbJsonControlImpl?.delThisMdc(mdcClient.ip, mdcClient.port);
    }
  }

  @override
  void onClose() {
    super.onClose();
    // 关闭所有流控制器
    stateStream.close();
    orderStream.close();
    mdcStateStream.close();

    _subscriptions.dispose();

    _mdcDefaultControl?.dispose();

    // 停止所有 MDC 连接
    //mdcDefaultControl.delThisMdc(pzIPv4, uPort);
  }

  /// 根据枪号设置价格
  void setGunPriceByGunNos(List<GetConfigGunsEntity> data) {
    final List<MdcSetPrcNzlCmdBeanPrcOil> listPrcOil = [];
    for (final oil in data) {
      if (oil.goodsSkuPrice != null && oil.goodsSkuPrice!.isNotEmpty) {
        oil.shelfList?.forEach((shelf) {
          listPrcOil.add(
            MdcSetPrcNzlCmdBeanPrcOil()
              ..nzl = shelf.shelfNo ?? 0
              ..prc = oil.goodsSkuPrice?.toFen ?? 0,
          );
        });
      }
    }
    _mdcDefaultControl?.setGunPriceByGunNo(listPrcOil);
    _mdcHbJsonControlImpl?.setGunPriceByGunNo(listPrcOil);
  }
}
